<template>
    <div id="EnterpriseUnitReview">
        <div class="content">
            <div class="list">
                <van-form validate-first>
                    <p class="subTitle"><span class="line"></span>测绘协同信息</p>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.CLR" label="处理人" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field readonly clickable name="datetimePicker" :value="formData.CLSJ" label="处理时间"
                            placeholder="请选择" @click="showPickerq = true" />
                        <van-popup v-model="showPickerq" position="bottom">
                            <van-datetime-picker v-model="currentDate" type="date" title="选择年月日"
                                @cancel="showPickerq = false" @confirm="onConfirmRQ" />
                        </van-popup>
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SJFJZDMJ" label="实际房基地占地面积（m²）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SJZDMJ" label="实际占地面积（m²）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SJCS" label="实际层数（层）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SJGD" label="实际高度（m）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SJJZMJ" label="实际建筑面积（m²）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.ZDH" label="宗地号" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SZGC1" label="四周高程1（米）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SZGC2" label="四周高程2（米）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SZGC3" label="四周高程3（米）" placeholder="请输入" />
                    </div>
                    <div class="inputWrap">
                        <span style="color: #FF0000;">*</span>
                        <van-field v-model="formData.SZGC4" label="四周高程4（米）" placeholder="请输入" />
                    </div>
                </van-form>
            </div>
            <div v-for="(item, index) in fileData" :key="index" style="border-bottom: 1px solid #ebedf0">
                <template v-if="item.name == '坐标串'">
                    <div style="display: flex;justify-content: space-between;">
                        <span style="font-size: 14px;font-weight: bold;line-height:44px; color: #646566;">
                            <!-- <span style="color: #FF0000;margin-right:10px">*</span> -->
                            坐标串
                        </span>
                        <van-uploader @click-upload="getList(item)" @click-preview="lookFile" :after-read="afterRead"
                            :before-delete="delectFile" v-model="item.fileList" :max-count="1"
                            accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx" style="margin-top:10px;">
                            <van-button icon="plus" type="info" plain size="mini">上传TXT文件</van-button>
                        </van-uploader>
                    </div>
                </template>
                <template v-else-if="item.name == '坐标文件'">
                    <div style="display: flex;justify-content: space-between;">
                        <span style="font-size: 14px;font-weight: bold;line-height:44px; color: #646566;">
                            <!-- <span style="color: #FF0000;margin-right:10px">*</span> -->
                            坐标文件
                        </span>
                        <van-uploader @click-upload="getList(item)" @click-preview="lookFile" :after-read="afterRead"
                            :before-delete="delectFile" v-model="item.fileList" :max-count="1"
                            accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx" style="margin-top:10px;">
                            <van-button icon="plus" type="info" plain size="mini">上传CAD文件</van-button>
                        </van-uploader>
                    </div>
                </template>
                <template v-else-if="item.name == '测绘报告'">
                    <div style="display: flex;justify-content: space-between;">
                        <span style="font-size: 14px;font-weight: bold;line-height:44px; color: #646566;">测绘报告</span>
                        <van-uploader @click-upload="getList(item)" @click-preview="lookFile" :after-read="afterRead"
                            :before-delete="delectFile" v-model="item.fileList" :max-count="1"
                            accept=".jpg,.gif,.png,.jpeg,.txt,.pdf,.doc,.docx,.xls,.xlsx" style="margin-top:10px;">
                            <van-button icon="plus" type="info" plain size="mini">上传</van-button>
                        </van-uploader>
                    </div>
                </template>
                <template v-else>
                    <p style="font-size: 14px;font-weight: bold;line-height:44px; color: #646566;">
                        {{ item.name }}
                    </p>
                    <van-uploader @click-upload="getList(item)" :after-read="afterRead" :before-delete="delectFile"
                        v-model="item.fileList" multiple />
                </template>
            </div>
            <div style="margin:10px 0;background: #EEF5FF;padding:10px;">
                <p style="font-size:16px;font-weight: bold;margin:6px 0">测绘提示：</p>
                <p style="font-size:14px">
                    测绘公司必须上传CAD文件和相关的坐标串文件，其中坐标串文件格式要求：文件为两列，第一列X轴坐标信息。第二列Y轴坐标信息，每行一组X轴、Y轴信息。坐标系必须使用2000国家大地坐标系。
                </p>
            </div>

            <div class="footer">
                <van-button style="margin-right: 10px;width: 24vw;" size="small" type="info" @click="getinsertDataView()">提交
                </van-button>
                <van-button style="margin-right: 10px;width: 24vw;" size="small" type="info" @click="save()">保存</van-button>
                <van-button style="margin-right: 10px;width: 24vw;" size="small" type="info" @click="getDituUrl">地图</van-button>
            </div>
        </div>
    </div>
</template>
<script>
import { QuerySignCallback, dataTransFile, dataTransFilePreview } from '@/utils/api'
import dd from "gdt-jsapi";
export default {
    data() {
        return {
            showEdition: false,
            row: {},
            rowGuid: "",
            formData: {
                CLR: "",
                CLSJ: "",
                SJFJZDMJ: "",
                SJZDMJ: "",
                SJCS: "",
                SJGD: "",
                SJJZMJ: "",
                ZDH: "",
                SZGC1: "",
                SZGC2: "",
                SZGC3: "",
                SZGC4: "",
            },
            fileData: [
                {
                    name: "现场照片1",
                    groupGuid: "9396d4c6-5715-479e-800c-cfb5f4a40e82",
                    fileList: [],
                },
                {
                    name: "现场照片2",
                    groupGuid: "c531d510-436c-4be3-99ca-bc9999739415",
                    fileList: [],
                },
                {
                    name: "现场照片3",
                    groupGuid: "d4160215-7f83-477d-acd9-54c57197dcc9",
                    fileList: [],
                },
                {
                    name: "坐标文件",
                    groupGuid: "ad2bd6ce-ff46-4a19-a6b1-cfc0bbd64daf",
                    fileList: [],
                },
                {
                    name: "坐标串",
                    groupGuid: "725b5997-51d2-4381-937a-4d826c2a3406",
                    fileList: [],
                },
                {
                    name: "竣工平面简图",
                    groupGuid: "bcd764be-fa78-43df-baf2-646a54244126",
                    fileList: [],
                },
                {
                    name: "测绘报告",
                    groupGuid: "18450870-ac41-4089-be09-f960b9bd37ab",
                    fileList: [],
                },
            ],
            showPickerq: false,
            currentDate: new Date(),
        }
    },
    watch: {},
    methods: {
        afterRead(file) {
            // 此时可以自行将文件上传至服务器
        },
        //下拉时间选择
        onConfirmRQ(val) {
            let year = val.getFullYear();
            let month = val.getMonth() + 1;
            let day = val.getDate();
            let hour = val.getHours();
            let minute = val.getMinutes();
            if (month >= 1 && month <= 9) {
                month = `0${month}`;
            }
            if (day >= 1 && day <= 9) {
                day = `0${day}`;
            }
            if (hour >= 0 && hour <= 9) {
                hour = `0${hour}`;
            }
            if (minute >= 0 && minute <= 9) {
                minute = `0${minute}`;
            }
            this.formData.CLSJ = `${year}-${month}-${day}`;
            this.showPickerq = false;
        },
        //获取相关材料
        getFile: async function () {
            let groupGuid = [];
            this.fileData.forEach((item) => {
                groupGuid.push(item.groupGuid);
            });
            let params1 = {
                "accessCode": "1fdcbce42c6d4748a020feba618d54b8",
                "cityCode": window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
                "params": {
                    "groupGuid": groupGuid.join(","),
                    "toRowGuid": this.row.ROW_GUID,
                    "token": window.localStorage.getItem('token')
                }
            }
            const res1 = await QuerySignCallback(params1)
            let data = JSON.parse(res1.data.data).FilesInfo
            if (data.length > 0) {
                data.forEach((element) => {
                    this.fileData.forEach((item) => {
                        if (element.GROUPGUID == item.groupGuid) {
                            if (item.name == '坐标文件' || item.name == '坐标串' || item.name == '测绘报告') {
                                element["isImage"] = false;
                                element['file'] = {
                                    name: element.FILENAME
                                }
                            } else {
                                element["isImage"] = true;
                            }
                            this.getFileUrl(element,item)
                        }
                    });
                });
            }
        },
        //获取附件文件流
        getFileUrl: async function (element, item) {
            let formData = new FormData();
            formData.append("accessCode", "98bcf528966e48ce896a8b3fd02d45d5");
            formData.append(
                "cityCode",
                window.localStorage.getItem("citycode")
                    ? window.localStorage.getItem("citycode")
                    : "441300000000"
            );
            formData.append(
                "paramStr",
                JSON.stringify({
                    fileGuid: element.ROW_GUID,
                })
            );
            let response = await dataTransFilePreview(formData);
            if (response) {
                var img = new Blob([new Int8Array(response.data, 0)], {
                    type: response.headers["content-type"],
                });
                element["url"] = window.URL.createObjectURL(img);
                item.fileList.push(element);
            }
        },
        //相关材料
        getList(item) {
            this.groupGuids = item.groupGuid;
        },
        afterRead(file) {
            // 此时可以自行将文件上传至服务器
            this.getFileServerUpload(file.file);
        },
        //预览上传附件
        lookFile(item) {
            if (item.isImage == false) {
                dd.ready(function () {
                    dd.openLink({
                        url: item.url,
                    }).then((res) => {
                    }).catch((err) => {
                        console.error(err);
                    });
                });
            }
        },
        //删除附件
        delectFile: async function (file) {
            if (file.ROW_GUID) {
                let params = {
                    accessCode: "ce9b691634de4ebca68dc5bb638d07f4",
                    cityCode: window.localStorage.getItem("citycode")
                        ? window.localStorage.getItem("citycode")
                        : "441300000000",
                    params: {
                        fileGuid: fileguid,
                        token: window.localStorage.getItem("token"),
                    },
                };
                const res = await QuerySignCallback(params);
                let data = JSON.parse(res.data.data).Success;
                if (data) {
                    this.$toast.success("删除成功!");
                }
            }
        },
        //上传附件
        getFileServerUpload: async function (file) {
            let data = {
                toRowGuid: this.row.ROW_GUID,
                groupGuid: this.groupGuids,
                token: window.localStorage.getItem("token"),
            };
            let formData = new FormData();
            formData.append("file", file);
            formData.append("accessCode", "7a3fc061c866434b8475d3775c9ddcea");
            formData.append("cityCode", window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000');
            formData.append("token", window.localStorage.getItem("token"));
            formData.append("paramStr", JSON.stringify(data));
            const res = await dataTransFile(formData);
            let data1 = JSON.parse(res.data.data).FileList;
            this.fileGuid = data1[0].FILEGUID;
            if (data1[0].FILEGUID) {
                this.$toast.success("上传成功!");
                this.fileData.forEach((item, index) => {
                    item.fileList = [];
                });
                this.getFile();
            }
        },
        getNowTime: function () {
            let dateTime;
            let yy = new Date().getFullYear();
            let mm =
                new Date().getMonth() + 1 < 10
                    ? "0" + (new Date().getMonth() + 1)
                    : new Date().getMonth() + 1;
            let dd =
                new Date().getDate() < 10
                    ? "0" + new Date().getDate()
                    : new Date().getDate();
            let hh = new Date().getHours();
            let mf =
                new Date().getMinutes() < 10
                    ? "0" + new Date().getMinutes()
                    : new Date().getMinutes();
            let ss =
                new Date().getSeconds() < 10
                    ? "0" + new Date().getSeconds()
                    : new Date().getSeconds();
            dateTime = yy + "-" + mm + "-" + dd;
            return dateTime;
        },
        //提交
        getinsertDataView() {
            this.save('submit')
        },
        //保存
        save: async function (type) {
            let me = this
            let state = true
            // me.fileData.forEach((item, index) => {
            //     if (item.fileList.length == 0) {
            //         if (item.name == '坐标串' || item.name == '坐标文件') {
            //             me.$toast.success('请上传附件！')
            //             state = false
            //         }
            //     }
            // })
            if (state) {
                if (me.formData.CLR && me.formData.CLSJ && me.formData.SJFJZDMJ && me.formData.SJZDMJ && me.formData.SJCS && me.formData.SJGD
                    && me.formData.SJZDMJ && me.formData.ZDH && me.formData.SZGC1 && me.formData.SZGC2 && me.formData.SZGC3 && me.formData.SZGC4) {
                    let accessCode = '77ad6c1591e54d4fbc45ecc90374a2a2'
                    if (!me.formData.ROW_GUID) {
                        accessCode = '0fb3f6123d1b4fe6851c99532c463f6f'
                        me.formData['ROW_GUID'] = me.rowGuid
                        me.formData['TO_ROW_GUID'] = me.row.ROW_GUID
                    }
                    let params = {
                        dataGuid: "64507058-ec6e-405b-9971-48e22a2e723b",
                        strParams: JSON.stringify([me.formData]),
                        token: window.localStorage.getItem('token')
                    }
                    let params1 = {
                        accessCode: accessCode,
                        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
                        params: params
                    }
                    const res = await QuerySignCallback(params1)
                    if (type && eval('(' + res.data.data + ')').Success == true) {
                        me.$router.push({
                            path: "/TreeSelect1",
                            query: {
                                data: me.row,
                                isqydw: 1,
                            },
                        });
                    } else if (eval('(' + res.data.data + ')').Success == true) {
                        me.$toast.success('成功！')

                    } else {
                        me.$toast.fail(res.data.msg)
                    }
                } else {
                    me.$toast.success('请输入必填项！')
                }
            }
        },
        //地图
        getDituUrl() {
            this.$router.push({
                path: "/mapContainer",
                query: {
                data: JSON.stringify(this.$route.query.data),
                },
            });
        },
        //查询信息
        getData: async function () {
            let params = {
                dataguid: "64507058-ec6e-405b-9971-48e22a2e723b",
                searchObject: JSON.stringify([{ field: 'TO_ROW_GUID', value: this.row.ROW_GUID, link: 'OR', operator: '=' }]),
            }
            let params1 = {
                accessCode: '688bd3883572440a859dfd8ba9194e7b',
                cityCode: window.localStorage.getItem("citycode") ? window.localStorage.getItem("citycode") : "441300000000",
                params: params
            }
            const res = await QuerySignCallback(params1)
            let data = eval('(' + res.data.data + ')').Data
            if (data.length > 0) {
                this.formData = data[0];
                this.formData.CLSJ = this.formData.CLSJ ? this.formData.CLSJ.split(" ")[0] : ""
                this.rowGuid = this.formData.ROW_GUID
                this.getFile();
            } else {
                this.formData.CLSJ = this.getNowTime()
                this.rowGuid = this.newGuid();
            }
        }
    },
    mounted() {
        this.row = JSON.parse(this.$route.query.data)
        this.getData()
        if (ZWJSBridge) {
            ZWJSBridge.setTitle({
                "title": "竣工验收"
            }).then(res => {
            }).catch(err => {
            })
        }
    },
}
</script>
<style scoped lang="scss">
#EnterpriseUnitReview {
    height: 100vh;
    overflow: auto;
    background: #ffffff;
    font-size: 14px;

    .van-field__label {
        font-weight: bold;
    }

    .content {
        width: 100%;
        height: auto;
        background: #ffffff;
        padding: 10px;

        .subTitle {
            width: 100%;
            height: 50px;
            line-height: 50px;
            font-size: 20px;
            position: relative;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #9b9b9b;
            padding-left: 10px;

            .line {
                width: 6px;
                height: 26px;
                background: #3f8ffc;
                display: inline-block;
                margin-right: 10px;
            }
        }

        .inputWrap {
            width: 100%;
            display: flex;
            justify-content: center;
            border-bottom: 1px solid #ebedf0;

            &>span {
                margin-right: 5px;
                margin-top: 15px;
            }
        }
    }

    .footer {
        display: flex;
        justify-content: center;
        padding: 10px 0;
    }
}
</style>
<style lang="scss">
#EnterpriseUnitReview {
    .van-cell {
        padding: 10px 0;
    }

    .van-field__label {
        font-weight: bold;
        width: auto !important;
    }

    .van-field__control {
        text-align: right;
    }
}
</style>